package com.hhit.bigscreenbackmanage.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class WlwspUtil {

	public static String getDataClient(JSONObject paramJson, String serverPath) throws Exception{
		
//		HttpClient client = new HttpClient();
//		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//		client.getHttpConnectionManager().getParams().setSoTimeout(30000);//设置超时响应时间
//		PostMethod post = new PostMethod(serverPath);
//		NameValuePair param[] = {new NameValuePair("param",  paramJson.toString())};
//		post.setRequestBody(param);
//
//        int result = client.executeMethod(post);
//        String res = post.getResponseBodyAsString();
//    	post.releaseConnection();
//    	if(result != 200) {
//    		System.out.println("调用数据服务失败：服务器端返回信息："+res);
//    		throw new ApplicationException("调用数据服务失败：服务器端返回HTTP code " + result+"\n信息："+res);
//        }
//    	else{
//    		JSONObject resultObj = new JSONObject(res);
//    		if(resultObj!=null&&resultObj.getBoolean("success")==false){
//    			System.out.println("调用数据服务失败：服务器端返回信息："+res);
//    			throw new Exception("调用数据服务失败：服务器端返回信息："+res);
//    		}
//        	return res;
//    	}
        //创建HttpClinet，
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(serverPath);
        //参数
        StringEntity s = new StringEntity(paramJson.toString(),"utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
        //
        httpPost.setEntity(s);
        httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
//        httpPost.setHeader(HTTP.USER_AGENT,"");
        // 使用HttpClient发起请求，返回response
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String res ="";
        if(entity!=null){
            res= EntityUtils.toString(entity,"utf-8");
        }
        EntityUtils.consume(entity);
        response.close();
        return  res;
	}


        /**
         * 获取物联网接口参数
         * @param
         * @param method
         * @param param
         * @return
         * @throws JSONException
         */
        public static JSONObject getWlwParamJson(String severpath,String method, JSONObject param) throws JSONException {

                JSONObject paramJson= new JSONObject();

                long timestamp = new Date().getTime();
                int nonce = 0;
                try {
                        SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
                        nonce=rand.nextInt(1000);
                } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                }
                String vue = "POST"+severpath+"?systemCode=QGCZHGLXT&timestamp="+timestamp+"&nonce="+nonce;
                String signature = sha256(vue,"QPJGM3CG7ZGfH8VG2bLLVXVlT");

                JSONObject fetchType=new JSONObject();
                fetchType.put("method", method);
                fetchType.put("systemCode", "QGCZHGLXT");
                fetchType.put("timestamp", timestamp);
                fetchType.put("nonce", nonce);
                fetchType.put("signature", signature);
                //参数
                paramJson.put("requestHead", fetchType);
                paramJson.put("requestBody", param);
                return paramJson;
        }

        /**
         * 生成签名
         * @param input
         * @param
         * @return
         */
        public static String sha256(String input, String salt)  {
                MessageDigest mDigest;
                StringBuffer sb = new StringBuffer();
                try {
                        mDigest = MessageDigest.getInstance("SHA-256");
                        mDigest.update(salt.getBytes());
                        byte[] result = mDigest.digest(input.getBytes());

                        for (int i = 0; i < result.length; i++) {
                                sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
                        }
                } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                }
                return sb.toString();
        }


}
